package com.elcom.player;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.elcom.player.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class Setting extends Activity{
	private String serverSub = "http://subscene.com";
	private boolean subtitlesize_changed = false;
	private boolean subtitle_changed = false;
	private boolean subtitlefontfile_changed = false;
	private boolean subtitlesubfile_changed = false;
	private boolean subtitlesubpos_changed = false;
	private boolean subtitlesubcol_changed = false;
	
	private boolean subtitle_state;
	private int subtitlesize_state;
	private String subtitlefontfile_state;
	private String subtitlesubfile_state;
	private int subtitlesubpos_state;
	private int subtitlesubcol_state;
	
	
	private TextView tvsubtitleFontFileSelected ;
	private TextView tvsubtitleSubFileSelected;
	private TextView tvsubtitlesizeSelected;
	private TextView tvsubtitleSubPosSelected;
	private TextView tvsubtitleSubColSelected;
	
	private CheckBox subtitle_bx; 
	
	Context context;
	private String subtitlesize[];
	private String subtitlepos[];
	private String subtitlecol[];
	private Intent is = new Intent();
	//Subtitle Server
	private ArrayList<String> mListSubServer;
	private ArrayList<String> listFilm;
	private ArrayList<String> listFilmUrl;
	private ArrayAdapter<String> mAdapter;
	private CustomAdapter mAdapterSub;
	private String urlServer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		context = getApplicationContext();
		Intent i = getIntent();
		
		subtitle_state = i.getExtras().getBoolean("SUBTITLE");
		subtitlesize_state = i.getExtras().getInt("SUBTITLESIZE");
		subtitlefontfile_state = i.getExtras().getString("SUBTITLEFONT");
		subtitlesubfile_state = i.getExtras().getString("SUBTITLEFILE");
		subtitlesubpos_state = i.getExtras().getInt("SUBTITLEPOS");
		subtitlesubcol_state = i.getExtras().getInt("SUBTITLECOL");
		

		
		subtitle_bx = (CheckBox)findViewById(R.id.setting_subtitlehide_box);

		
		final TableRow tblrowShowSubTitles = (TableRow)findViewById(R.id.tblrowshowsubtitles);
		final TableRow tblrowSubtitleSize = (TableRow)findViewById(R.id.tblrowsubtitlesize);
		final TableRow tblrowsubtitleFontFile = (TableRow)findViewById(R.id.tblrowsubtitlefontfileselected);
		final TableRow tblrowsubtitleSubtFile = (TableRow)findViewById(R.id.tblrowsubtitlesubfileselected);
		final TableRow tblrowsubtitleSubtPos = (TableRow)findViewById(R.id.tblrowsubtitlesubposselected);
		final TableRow tblrowsubtitleSubtCol = (TableRow)findViewById(R.id.tblrowsubtitlesubcolselected);
	  
		tvsubtitleFontFileSelected = (TextView)findViewById(R.id.subtitlefontfileselected);
		tvsubtitleSubFileSelected = (TextView)findViewById(R.id.subtitlesubfileselected);
		tvsubtitlesizeSelected = (TextView)findViewById(R.id.subtitleSizeSelected);
		tvsubtitleSubPosSelected = (TextView)findViewById(R.id.subtitlesubposselected);
		tvsubtitleSubColSelected = (TextView)findViewById(R.id.subtitlesubcolselected);
		
		subtitlesize = getResources().getStringArray(R.array.SubtitleSize);
		subtitlepos = getResources().getStringArray(R.array.SubtitlePos);
		subtitlecol = getResources().getStringArray(R.array.SubtitleCol);
		
		
		//init data 
		
		tvsubtitleSubFileSelected.setText(subtitlesubfile_state);
		tvsubtitleFontFileSelected.setText(subtitlefontfile_state);
		subtitle_bx.setChecked(subtitle_state);
		if(subtitlesize_state < subtitlesize.length)
			tvsubtitlesizeSelected.setText(subtitlesize[subtitlesize_state]);
		if(subtitlesubpos_state < subtitlepos.length)
			tvsubtitleSubPosSelected.setText(subtitlepos[subtitlesubpos_state]);
		if(subtitlesubcol_state < subtitlecol.length)
			tvsubtitleSubColSelected.setText(subtitlecol[subtitlesubcol_state]);
		
		//set listener
		tblrowsubtitleSubtCol.setOnClickListener(subtitleSubColClickListener);
		tblrowsubtitleSubtPos.setOnClickListener(subtitleSubPosClickListener);
		tblrowsubtitleSubtFile.setOnClickListener(subtitleSubFileClickListener);
		tblrowsubtitleFontFile.setOnClickListener(subtitleFontFileClickListener);
		tblrowSubtitleSize.setOnClickListener(subtitlesizeOnClickListener);
		tblrowShowSubTitles.setOnClickListener(subtitleOnCliclListener);		
		
		
	}
	OnClickListener subtitleSubColClickListener =	new OnClickListener(){
		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
			builder.setTitle(R.string.subtitlecol);
			builder.setItems(R.array.SubtitleCol, new DialogInterface.OnClickListener() {					
				@Override
				public void onClick(DialogInterface dialog, int index) {
					if(index < subtitlecol.length){
						subtitlesubcol_state = index;
						subtitlesubcol_changed = true;
						is.putExtra("SUBTITLECOL", subtitlesubcol_state);
						tvsubtitleSubColSelected.setText(subtitlecol[index]);
					}
				}
			});

			builder.create().show();
		}
	};
	OnClickListener subtitleSubPosClickListener =	new OnClickListener(){
		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
			builder.setTitle(R.string.subtitlepos);
			builder.setItems(R.array.SubtitlePos, new DialogInterface.OnClickListener() {					
				@Override
				public void onClick(DialogInterface dialog, int index) {
					if(index < subtitlepos.length){
						subtitlesubpos_state = index;
						subtitlesubpos_changed = true;
						is.putExtra("SUBTITLEPOS", subtitlesubpos_state);
						tvsubtitleSubPosSelected.setText(subtitlepos[index]);
					}
				}
			});

			builder.create().show();
		}
	};
	OnClickListener subtitleOnCliclListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			if (subtitle_bx.isChecked()){
				subtitle_bx.setChecked(false);
			}else{
				subtitle_bx.setChecked(true);
			}
			subtitle_state = subtitle_bx.isChecked();
			subtitle_changed = true;
			is.putExtra("SUBTITLE", subtitle_state);
	
		}
	};
	OnClickListener subtitlesizeOnClickListener =new OnClickListener() {
		@Override
		public void onClick(View view) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);

			builder.setTitle(R.string.subtitlesize);
			builder.setItems(R.array.SubtitleSize, new DialogInterface.OnClickListener() {					
				@Override
				public void onClick(DialogInterface dialog, int index) {
					if(index < subtitlesize.length){
						subtitlesize_state = index;
						subtitlesize_changed = true;
						is.putExtra("SUBTITLESIZE", subtitlesize_state);
						tvsubtitlesizeSelected.setText(subtitlesize[index]);
					}
				}
			});

			builder.create().show();
		}
	}; 
	OnClickListener subtitleFontFileClickListener =	new OnClickListener(){
		//System.out.println("inside OnClickListener");
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
			builder.setTitle("Select file font");
			ListView modeList = new ListView(Setting.this);
			FileManager flmg ;
			EventHandler handler ;
			EventHandler.TableRow  table ;
			flmg = new FileManager();
			handler = new EventHandler(Setting.this, flmg,Globals.MANAGER_TYPE_SUBFONT);
			table = handler.new TableRow();
			modeList.setAdapter(table);
			builder.setView(modeList);
			final Dialog dialog = builder.create();
			dialog.show();
			modeList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					
					subtitlefontfile_state = Globals.defaultDir + arg0.getItemAtPosition(arg2);
					tvsubtitleFontFileSelected.setText(subtitlefontfile_state);
					subtitlefontfile_changed = true;
					is.putExtra("SUBTITLEFONT", subtitlefontfile_state);
					toast("selected font:"+subtitlefontfile_state);
					dialog.dismiss();
				}
				
			});
		}
	};
	OnClickListener subtitleSubFileClickListener =	new OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
			builder.setTitle("Select file sub");
			ListView modeList = new ListView(Setting.this);
			FileManager flmg;
			EventHandler handler;
			EventHandler.TableRow  table=null;
			builder.setView(modeList);
			final Dialog dialog = builder.create();
			dialog.show();
			if(!Globals.fileName.contains("http://")){	//subtitle from local
				flmg = new FileManager();
				handler = new EventHandler(Setting.this, flmg,Globals.MANAGER_TYPE_SUBTITLE);
				table = handler.new TableRow();
				modeList.setAdapter(table);
				urlServer = Globals.defaultDir;
			}else{	 								//subtitle from server
				if(Globals.fileName.lastIndexOf("/") != -1)
					urlServer = Globals.fileName.substring(0,Globals.fileName.lastIndexOf("/")) + "/";
				mListSubServer = new ArrayList<String>();
				new PaserTask().execute(urlServer,"server");

				mAdapterSub =  new CustomAdapter(Setting.this, mListSubServer);
				modeList.setAdapter(mAdapterSub);
			}
			//Select Subttile
			modeList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					if(!Globals.fileName.contains("http://")){
						subtitlesubfile_state = urlServer + arg0.getItemAtPosition(arg2);
						tvsubtitleSubFileSelected.setText(subtitlesubfile_state);
						subtitlesubfile_changed = true;
						is.putExtra("SUBTITLEFILE", subtitlesubfile_state);
						dialog.dismiss();
					}else{
						if(arg2 != mListSubServer.size()-1){
							subtitlesubfile_state = urlServer + mListSubServer.get(arg2);
							tvsubtitleSubFileSelected.setText(subtitlesubfile_state);
							subtitlesubfile_changed = true;
							is.putExtra("SUBTITLEFILE", subtitlesubfile_state);
							dialog.dismiss();
						}else{
							listFilm = new ArrayList<String>();
							toast("search sub on intenet");
							AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
							builder.setTitle("Select film ");
							ListView modeList = new ListView(Setting.this);			
							mAdapter = new ArrayAdapter<String>(Setting.this,
									  android.R.layout.simple_list_item_1, 
									  android.R.id.text1,listFilm){
								@Override
								public View getView(int position, 
										View convertView, 
										android.view.ViewGroup parent) {
									View view =super.getView(position, convertView, parent);
									view.setBackgroundColor(Color.WHITE);
									return view;
								};
							};
							modeList.setAdapter(mAdapter);
							builder.setView(modeList);
							final Dialog dialog = builder.create();
							dialog.show();
							//Select Subttile
							modeList.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(AdapterView<?> arg0, View arg1,
										int arg2, long arg3) {
									// TODO Auto-generated method stub
									toast(listFilmUrl.get(arg2));
									dialog.dismiss();
									new PaserTask().execute(serverSub+listFilmUrl.get(arg2),"searchsub");
								}
								
							});
							
							new PaserTask().execute(serverSub+
									"/subtitles/title.aspx?q="+Globals.fileTitle+"&l=","searchfilm");
						}
					}
				}
			});
		}
	};
	
	private class PaserTask extends AsyncTask<String, Void, Integer>{
		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			if(params[1].equals("server")){
				try {
					Document doc = Jsoup.connect(params[0]).get();
					Elements eles = doc.select("td > a");
					Iterator<Element> ite = eles.iterator();
					while(ite.hasNext()){
						Element ele = ite.next();
						if(ele.select("a").first() != null){
							if(ele.select("a").attr("href").contains(".srt")){
								mListSubServer.add(ele.select("a").attr("href"));
								log(ele.text());
							}
						}
					}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return 1;
			}else if(params[1].equals("searchfilm")){
				try {
					listFilmUrl = new ArrayList<String>();
					Document doc = Jsoup.connect(params[0]).get();
					Element eleHeadPopular = doc.select("h2[class=popular]").first();
					if(eleHeadPopular!=null){
						Element elePopular= eleHeadPopular.nextElementSibling();
						Elements eles = elePopular.select("a");
						Iterator<Element> ite = eles.iterator();
						while(ite.hasNext()){
							Element ele = ite.next();
							if(ele != null){
								listFilm.add(ele.text());
								listFilmUrl.add(ele.attr("href"));
								log(ele.attr("href"));
							}
						}
						
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return 2;
			}else if(params[1].equals("searchsub")){
				try {
					if(mListSubServer.size() > 0)	mListSubServer.remove(mListSubServer.size()-1);
					Document doc = Jsoup.connect(params[0]).get();
					Element eleHead = doc.select("thead").first();
					if(eleHead!=null){
						Element elePopular= eleHead.nextElementSibling();
						Elements eles = elePopular.select("tr");
						Iterator<Element> ite = eles.iterator();
						while(ite.hasNext()){
							Element ele = ite.next();
							if(ele != null){
								mListSubServer.add(ele.select("span").text());
								log(ele.attr("href"));
							}
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return 3;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result==1){
				mListSubServer.add("Search sub on internet");
				mAdapterSub.notifyDataSetChanged();
			}else if(result == 2){
				mAdapter.notifyDataSetChanged();
			}else if(result == 3){
				mAdapterSub.notifyDataSetChanged();
			}
			
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		
	}
	void log(String ss){
		Log.d("EVPlayer",ss);
	}
	void toast(String ss){
		Toast.makeText(Setting.this, ss, Toast.LENGTH_SHORT).show();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(!subtitlesize_changed){
			is.putExtra("SUBTITLESIZE", subtitlesize_state);
		}
		if(!subtitle_changed){
			is.putExtra("SUBTITLE", subtitle_state);
		}
		if(!subtitlefontfile_changed){
			is.putExtra("SUBTITLEFONT", subtitlefontfile_state);
		}
		if(!subtitlesubfile_changed){
			is.putExtra("SUBTITLEFILE", subtitlesubfile_state);
		}
		if(!subtitlesubpos_changed){
			is.putExtra("SUBTITLEPOS", subtitlesubpos_state);
		}
		if(!subtitlesubcol_changed){
			is.putExtra("SUBTITLECOL", subtitlesubcol_state);
		}
		setResult(RESULT_CANCELED, is);
	}
}
